package com.gw2.gw2world.controller;

import java.net.URI;
import java.util.concurrent.Callable;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.net.Uri;

/** Download status of events in a thread
 *
 */
public class DownloadThread implements Callable<String> {
	private static final String TAG="DownloadThread";
	private static final String BASE_URL = "https://api.guildwars2.com/v1/events.json";
	private int server_id=0,  map_id=0;
	/** Prepare the thread with the given server
	 * @param sid Server ID
	 */
	public DownloadThread() {}
	
	public void setMap(int id) {map_id=id;}
	public void setServer(int id) {server_id=id;}
	/** Prepare the thread with the given server an map
	 * @param sid Server ID. If 0, it downloads from all servers
	 * @param mid map ID. If 0, it downloads from all maps
	 */
	public DownloadThread(int sid, int mid) {
		server_id=sid;
		map_id=mid;
	}

	@Override
	public String call() throws Exception {
		HttpClient client = new DefaultHttpClient();
		try {
			Uri.Builder ub=Uri.parse(BASE_URL).buildUpon();
			if(map_id!=0) ub.appendQueryParameter("map_id", String.valueOf(map_id));
			if(server_id!=0) ub.appendQueryParameter("world_id", String.valueOf(server_id));
			android.util.Log.d(TAG, "call(): URL: "+ub.build().toString());
			HttpGet request = new HttpGet(new URI(ub.build().toString()));
			request.addHeader("accept", "application/json");
			HttpResponse response = client.execute(request);
			return Tools.convertStreamToString(response.getEntity().getContent());
		}
		catch (Exception e) {e.printStackTrace();}
		return "[]";
	}
}
